﻿using AutoMapper;
using Decoration.Api.Comm;
using Decoration.IService;
using Decoration.Models;
using Decoration.Models.Dto;
using Decoration.Models.DTO;
using Decoration.Models.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Decoration.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginInfoController : ControllerBase
    {
        // GET: api/<LoginController>
        ILoginInfoService svc;
        private readonly IMapper mapper;

        public LoginInfoController(ILoginInfoService svc,IMapper mapper) {
            this.svc = svc;
            this.mapper = mapper;
        }

        // GET: api/<LoginInfoController>

        [HttpPost]
        [Route("login")]
        public Result Login(LoginInfoDto login)

        {
            Base_LoginInfo lg = svc.Query(o => o.LoginName == login.LoginName).Include(o => o.User).FirstOrDefault()!;
            //string loginPwd = Tools.Md5(login.LoginPwd, "X2");
            if (lg != null)
            {
                if (lg.LoginPwd == login.LoginPwd)
                {
                    if (lg.Status == 1)
                    {
                        AuthInfo auth = new AuthInfo();
                        auth.UserName = lg.User.UserName;
                        auth.UserId = lg.UserId;
                        string token = JwtHelper.CreateJwtToken(auth);
                        auth.Tx = lg.ProfilePhoto;
                        auth.token = token;

                        //修改登录次数
                        lg.LoginCount= lg.LoginCount + 1;

                        svc.Update(lg);
                        return new Result() { code = 1, msg = "登录成功", data = auth };
                    }
                    else
                    {
                        return new Result() { code = -1, msg = "账号异常!" };
                    }
                }
                else
                {
                    return new Result() { code = -1, msg = "密码错误!" };
                }
            }
            else
            {
                return new Result() { code = -1, msg = "账号错误!" };
            }
        }
        [HttpPost]
        [Route("Tellogin")]
        public Result LoginTel(TelPwdDto login)
        {
            var sql = @"select *from Base_UserInfos u
                    inner join Base_LoginInfos l
                    on u.Id = l.UserId 
                    where U.Tel = @Tel";
            var list = svc.Query<LoginTelDto>(sql, new { login.Tel}).ToList().First();

            //string loginPwd = Tools.Md5(login.LoginPwd, "X2");
            if (list != null)
            {
                if (list.LoginPwd == login.LoginPwd)
                {
                    if (list.Status == 1)
                    {
                        AuthInfo auth = new AuthInfo();
                        auth.UserName = list.UserName;
                        auth.UserId = list.Id;
                        string token = JwtHelper.CreateJwtToken(auth);
                        auth.Tx = list.ProfilePhoto;
                        auth.token = token;
                        return new Result() { code = 1, msg = "登录成功", data = auth };
                    }
                    else
                    {
                        return new Result() { code = -1, msg = "账号异常!" };
                    }
                }
                else
                {
                    return new Result() { code = -1, msg = "密码错误!" };
                }
            }
            else
            {
                return new Result() { code = -1, msg = "账号错误!" };
            }
        }

        [HttpGet]
        public PagedResult<Base_LoginInfo> Get(string? LogiName, int pageIndex = 1, int pageSize = 10)
        {
            var data = svc.Query(o => true);
            if (!string.IsNullOrEmpty(LogiName))
            {
                data = data.Where(o => o.LoginName.Contains(LogiName));
            }
            int total = data.Count();
            data = data.OrderByDescending(o => o.CreateTime).Skip(pageSize * (pageIndex - 1)).Take(pageSize);
            return new PagedResult<Base_LoginInfo>() { code = 1, msg = "成功", data = data, total = total };

        }

        // GET api/<LoginController>/5
        [HttpGet("{id}")]
        public Result Get(int id)
        {
            var info = svc.Get(o => o.Id == id);
            if (info == null)
            {
                return new Result() { code = -1, msg = "为查询到数据" };
            }
            return new Result() { code = 1, msg = "成功", data = info };

        }

        // POST api/<LoginController>
        [HttpPost]
        public Result Post(Base_LoginInfo lo)
        {
            var info = new Base_LoginInfo() {
                CreateTime = DateTime.Now,
                LoginName = lo.LoginName,
                LoginCount = 0,
                LoginLastTime = DateTime.Now,
                LoginPwd = lo.LoginPwd,
                OpenId = lo.OpenId,
                ProfilePhoto = lo.ProfilePhoto,
                Status = lo.Status,
                User = lo.User,
                UserId = lo.UserId,
            };
            if (info == null)
            {
                return new Result() { code = -1, msg = "为查询到数据" };
            }
            var res = svc.Add(info);
            return new Result() { code = 1, msg = "成功", data = res };
        }

        // PUT api/<LoginController>/5
        [HttpPut]
        public Result Put(LoginPutDto dto)
        {
            var getId = svc.Get(o => o.Id == dto.Id);
            if (getId == null)
            {
                return new Result() { code = -1, msg = "未查询到数据" };
            }

            mapper.Map(dto, getId);

            var res = svc.Update(getId);
            return new Result() { code = 1, msg = "成功", data = res };
        }

        // DELETE api/<LoginController>/5
        [HttpDelete("{id}")]
        public Result Delete(int id)
        {
            var getId = svc.Get(o => o.Id == id);
            if (getId == null)
            {
                return new Result() { code = -1, msg = "为查询到数据" };
            }
            getId.Status = 0;
            var res = svc.Update(getId);
            return new Result() { code = 1, msg = "成功", data = res };
        }

        [HttpPost]
        [Route("Changepwd")]
        public Result ChangePwd(LoginPwdDto dto) 
        {
            var info = svc.Get(o => o.UserId.Equals(dto.Id));
            if (info.LoginPwd!=dto.OldLoginPwd)
            {
                return new Result() { code = -1, msg = "当前密码错误" };
            }
            info.LoginPwd= dto.NewLoginPwd;

            var update = svc.Update(info);

            if (update==true) 
            {
                return new Result() { code = 1, msg = "成功" };
            }
            return new Result() { code = -1, msg = "失败" };

        }

        /// <summary>
        /// 根据用户id获取
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("getByUser")]
        public Result GetByUser(int userId)
        {
            var data = svc.Get(o=>o.UserId == userId);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            return new Result() { code = -1,msg="成功",data = data};
        }
    }
}
